//
//  RegistViewController.m
//  B项目
//
//  Created by lanou on 16/8/6.
//  Copyright © 2016年 Work. All rights reserved.
//

#import "RegistViewController.h"
#import "PrefixHeader.pch"
#import "comleteRegistViewController.h"
#import "YGValidator.h"
#import "MBProgressHUD.h"
#import <AVOSCloud/AVOSCloud.h>
@interface RegistViewController ()<UITextFieldDelegate>

@property(nonatomic,strong) UITextField *userTF;
@property(nonatomic,strong)UITextField *passWordUserTF;
@property(nonatomic,strong)MBProgressHUD *HUD;

//获取验证码
@property(nonatomic,strong)UIButton *button;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
     self.navigationItem.title = @"快速注册 - 验证手机";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.userTF.delegate= self;

    [self setRegist];
}

//点击返回
- (void)leftItemAction
{
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)setRegist
{
    UIView *userView = [[UIView alloc]initWithFrame:CGRectMake(20, 30, kScreenWidth - 40, 60)];

    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];
    //    userImg.backgroundColor = [UIColor redColor];
    userImg.image = [UIImage imageNamed:@"phone.png"];

    self.
    userTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, userView.ownWidth -40, 30)];
    _userTF.placeholder = @"请输入手机号码";
    _userTF.tag = 10;
    _userTF.delegate = self;
    _userTF.font = [UIFont systemFontOfSize:14];
    [_userTF setBorderStyle:(UITextBorderStyleNone)];
    [userView addSubview:_userTF];
    [userView addSubview:userImg];
    [userView addSubview:lineView];
    [self.view addSubview:userView];


    UIView *passWordView = [[UIView alloc]initWithFrame:CGRectMake(20, 90, kScreenWidth - 40, 60)];
    passWordView.userInteractionEnabled = YES;

    UIView *lineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, userView.ownWidth, 1)];
    lineViewP.backgroundColor = [UIColor grayColor];
    UIImageView *passWordImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];
    passWordImg.image = [UIImage imageNamed:@"yanzheng.png"];

    self.passWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, passWordView.ownWidth -120, 30)];
    _passWordUserTF.placeholder = @"请输入验证码";
    _passWordUserTF.tag = 11;
    _passWordUserTF.delegate = self;
    _passWordUserTF.font = [UIFont systemFontOfSize:14];
    [_passWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    self.button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _button.frame = CGRectMake(passWordImg.ownWidth + _passWordUserTF.ownWidth, 10, 100, 30);
    [_button setTitle:@"获取验证码" forState:(UIControlStateNormal)];
    _button.titleLabel.font = [UIFont systemFontOfSize:12];
    //    _button.backgroundColor = [UIColor greenColor];
    //    _button.alpha = 0.3;
    //    _button.layer.cornerRadius = 5;
    //    _button.layer.masksToBounds = YES;
    [_button setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    [_button addTarget:self action:@selector(btAction) forControlEvents:(UIControlEventTouchUpInside)];

    [passWordView addSubview:lineViewP];
    [passWordView addSubview:_passWordUserTF];
    [passWordView addSubview:passWordImg];
    [passWordView addSubview:_button];
    [self.view addSubview:passWordView];

    UIImageView *RegistImg = [[UIImageView alloc]initWithFrame:CGRectMake(20, 180, kScreenWidth - 40, 30)];
    RegistImg.userInteractionEnabled = YES;
    RegistImg.image = [UIImage imageNamed:@"login_tip_button@2x.png"];
    UIButton *LoaginBT = [[UIButton alloc]initWithFrame:CGRectMake((RegistImg.ownWidth -60)/2, 0, 60, 30)];
    [LoaginBT setTitle:@" 下一步" forState:(UIControlStateNormal)];
    [LoaginBT setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [LoaginBT addTarget:self action:@selector(registBTAction) forControlEvents:(UIControlEventTouchUpInside)];
    [RegistImg addSubview:LoaginBT];
    [self.view addSubview:RegistImg];

}



//点击验证码点击事件
- (void)btAction
{

    if ([_userTF.text isEqualToString:@""]) {
        [self showAlert:@"手机号码不能为空"];


    }else{
        if (_userTF.text.length != 11) {
            [self showAlert:@"手机号码格式不正确"];

        }else{
            __block int timeout=60; //倒计时时间

            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行

            dispatch_source_set_event_handler(_timer, ^{

                if(timeout<=0){ //倒计时结束，关闭

                    dispatch_source_cancel(_timer);

                    dispatch_async(dispatch_get_main_queue(), ^{

                        //设置界面的按钮显示 根据自己需求设置

                        [_button setTitle:@"重新获取" forState:UIControlStateNormal];

                        _button.userInteractionEnabled = YES;
                        [_button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];

                    });

                }else{

                    int seconds = timeout;

                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

                    dispatch_async(dispatch_get_main_queue(), ^{

                        //让按钮变为不可点击的灰色

                        //                        _button.backgroundColor = [UIColor grayColor];

                        [_button setTitleColor:[UIColor greenColor] forState:(UIControlStateNormal)];
                        _button.userInteractionEnabled = NO;

                        //设置界面的按钮显示 根据自己需求设置

                        [UIView beginAnimations:nil context:nil];

                        [UIView setAnimationDuration:1];

                        [_button setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];

                        [UIView commitAnimations];

                    });

                    timeout--;

                }

            });

            dispatch_resume(_timer);


            //获取验证码
            [AVOSCloud requestSmsCodeWithPhoneNumber:self.userTF.text callback:^(BOOL succeeded, NSError *error) {

                if (succeeded) {

                    [self showAlert:@"发送成功"];
                }else{

                    [self showAlert:@"发送失败"];

                }
                // 发送失败可以查看 error 里面提供的信息
            }];



        }


    }

}

//点击下一步的点击事件
- (void)registBTAction
{
    if ([_userTF.text isEqualToString:@""] || [_passWordUserTF.text isEqualToString:@""]) {
        [self showAlert:@"请补全信息"];
    }else{
        [AVOSCloud verifySmsCode:self.passWordUserTF.text mobilePhoneNumber:self.userTF.text callback:^(BOOL succeeded, NSError *error) {
            if(succeeded){
                NSLog(@"验证成功");
                [self showAlert:@"验证成功"];

                self.HUD = [[MBProgressHUD alloc]init];
                [self.view addSubview:self.HUD];
                self.HUD.dimBackground = YES;

                _HUD.mode = MBProgressHUDModeIndeterminate;
                _HUD.opacity = 0.5;
                //    _HUD.color = [UIColor clearColor];
                _HUD.color = [_HUD.color colorWithAlphaComponent:1];
                _HUD.labelFont = [UIFont systemFontOfSize:13];
                self.HUD.labelText = @"loading...";
                _HUD.minShowTime = 1.5;
                _HUD.cornerRadius = 20;
                _HUD.activityIndicatorColor = [UIColor redColor];
                _HUD.animationType = MBProgressHUDAnimationZoomIn;
                [_HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];

                comleteRegistViewController *completeRegistVC = [[comleteRegistViewController alloc]init];
                completeRegistVC.phoneNumber = self.userTF.text;
                [self.navigationController pushViewController:completeRegistVC animated:YES];

            }else{
                [self showAlert:@"验证失败"];

            }
        }];


    }

}


//任务，测试进度显示
- (void)myProgressTask {
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        _HUD.progress = progress;
        usleep(50000);
    }
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    NSMutableString *currentPassWordStr = [NSMutableString stringWithString:_userTF.text];
    [currentPassWordStr replaceCharactersInRange:range withString:string];
    [YGValidator validateText:currentPassWordStr regular:@"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$" textField:_userTF correctImage:@"true" errorImage:@"error"];
    return YES;
}


//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.tag != 11) {
        [[self.view viewWithTag:11] becomeFirstResponder];

    }else{
        [[self.view viewWithTag:11]resignFirstResponder];
    }

    return YES;
}


//提示框
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}


- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
